<script setup>
import { getAdverseAnalysis } from '@/api/visual/qualityDashboard'
import { formatMoney } from '@/utils/globalMethod'
import { ref } from 'vue'
import { useLocalStorage } from '@vueuse/core'
const key = ref(1)
const type = useLocalStorage('salesBoard9.type', 'month')

const xAxisData = ref([])
const yAxisData = ref([])
const yAxisData1 = ref([])
const option = computed(() => ({
  grid: {
    containLabel: true
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999'
      }
    }
  },

  xAxis: [
    {
      type: 'category',
      data: xAxisData.value,
      axisPointer: {
        type: 'shadow'
      },
      axisTick: {
        alignWithLabel: true
      },
      axisLabel: {
        color: '#ccc1c1'
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: '不良品数量',
      min: 0
    },
    {
      type: 'value',
      name: '累计频率',
      axisLabel: {
        formatter: '{value} %'
      }
    }
  ],
  series: [
    {
      name: '不良品数量',
      type: 'bar',
      tooltip: {
        valueFormatter: function (value) {
          // 添加千位分隔符
          return value.toLocaleString()
        }
      },
      data: yAxisData.value,
      label: {
        show: true,
        position: 'inside'
      }
    },
    {
      name: '累计频率',
      type: 'line',
      yAxisIndex: 1,
      data: yAxisData1.value,
      label: {
        show: true,
        position: 'inside',
        color: '#fff',
        formatter: function (params) {
          return params.value + '%'
        }
      }
    }
  ]
}))

const loadData = async () => {
  let { data } = await getAdverseAnalysis({ type: type.value })
  if (data.length === 0) {
    data = [
      { NotWellName: '无', PrdQuantity: 0 },
      { NotWellName: '无', PrdQuantity: 0 },
      { NotWellName: '无', PrdQuantity: 0 },
      { NotWellName: '无', PrdQuantity: 0 },
      { NotWellName: '无', PrdQuantity: 0 },
      { NotWellName: '无', PrdQuantity: 0 },
      { NotWellName: '无', PrdQuantity: 0 },
      { NotWellName: '无', PrdQuantity: 0 },
      { NotWellName: '无', PrdQuantity: 0 },
      { NotWellName: '无', PrdQuantity: 0 }
    ]
  }
  // 1. 计算总不良数
  const totalDefects = data.reduce((sum, item) => sum + item.PrdQuantity, 0)

  // 2. 按数量降序排序
  const sortedData = [...data].sort((a, b) => b.PrdQuantity - a.PrdQuantity)

  // 3. 拆分数据：前10个 + 其他
  const topItems = sortedData.slice(0, 10)
  const otherItems = sortedData.slice(10)

  // 4. 计算"其他"项的总和
  const otherTotal = otherItems.reduce((sum, item) => sum + item.PrdQuantity, 0)

  // 5. 合并数据（如果有其他项则添加）
  const combinedData = [...topItems]
  if (otherTotal > 0) {
    combinedData.push({
      NotWellName: '其他',
      PrdQuantity: otherTotal
    })
  }

  // 6. 计算频率和累计频率
  let cumulative = 0
  const result = combinedData.map(item => {
    const frequency = (item.PrdQuantity / totalDefects) * 100
    cumulative += frequency

    return {
      reason: item.NotWellName,
      count: item.PrdQuantity,
      frequency: Number(frequency.toFixed(2)),
      cumulative: Number(cumulative.toFixed(2))
    }
  })

  // 7. 清空图表数据
  xAxisData.value = []
  yAxisData.value = []
  yAxisData1.value = []

  // 8. 填充处理后的数据
  result.forEach(item => {
    xAxisData.value.push(item.reason)
    yAxisData.value.push(item.count)
    yAxisData1.value.push(item.cumulative)
  })
}
const keyResize = () => {
  nextTick(() => {
    setTimeout(() => {
      key.value++
    }, 100)
  })
}

onMounted(loadData)
onMounted(() => {
  window.addEventListener('resize', keyResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', keyResize)
})
</script>

<template>
  <div class="ps_w_h_100 salesBoard7">
    <dv-border-box10 :key="key">
      <el-card class="ps_w_h_100 salesBoard9-card">
        <template #header>
          <div class="salesBoard7-card-header board-title" style="display: flex">
            <span>不良品柏拉图分析</span>
            <div class="select" style="margin-left: auto">
              <select class="chart-select" v-model="type" @change="loadData">
                <option value="today">今天</option>
                <option value="week">本周</option>
                <option value="month">本月</option>
                <option value="season">本季</option>
                <option value="year">本年</option>
              </select>
            </div>
          </div>
        </template>

        <ps-chart2 :option="option"></ps-chart2>
      </el-card>
    </dv-border-box10>
  </div>
</template>

<style scoped lang="scss">
.salesBoard9 {
  &-card-header {
    display: flex;
    justify-content: space-between;

    .bq {
      margin-right: 20px;
    }
  }
}

:deep(.el-card) {
  background-color: transparent;
  border: unset;

  .el-card__body {
    padding: 0;
    height: 100%;
  }
}
</style>
